package com.shensi.adminCollect.controller.station;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shensi.adminCollect.common.constant.HttpStatus;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.station.dto.AddTeamManagement;
import com.shensi.adminCollect.domain.station.dto.MemberManagementDto;
import com.shensi.adminCollect.domain.station.dto.MemberManagementQueryDto;
import com.shensi.adminCollect.domain.station.dto.TeamManagementDto;
import com.shensi.adminCollect.domain.station.vo.MemberManagementVo;
import com.shensi.adminCollect.domain.station.vo.RegionalReportVo;
import com.shensi.adminCollect.domain.station.vo.TeamManagementVo;
import com.shensi.adminCollect.service.station.MemberManagementService;
import com.shensi.adminCollect.service.station.TeamManagementService;
import com.shensi.adminCollect.service.system.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;

/**
 * @Auther: zxy
 * @Date: 2023/8/29 16:17
 * @Description:
 */
@RestController
@RequestMapping("/team/message")
@Api(tags = "团队成员管理Controller")
@Slf4j
public class TeamManagementController extends BaseController {

    @Autowired
    private TeamManagementService teamManagementService;
    @Autowired
    private MemberManagementService memberManagementService;
    @Autowired
    private ISysUserService sysUserService;

    @PostMapping("/addTeam")
    @ApiOperation(value = "新增团队", notes = "新增团队")
    public AjaxResult addTeam(@RequestBody @Valid AddTeamManagement teamManagement) {
        log.info("新增团队入参：{}", teamManagement);
        AddTeamManagement addTeamManagement = teamManagementService.addTeam(teamManagement);
        return AjaxResult.success(addTeamManagement);
    }

    @DeleteMapping("/deleteTeam/{ids}")
    @ApiOperation(value = "删除团队", notes = "删除团队")
    @ApiImplicitParam(paramType = "path", name = "ids", value = "团队ID集合，多个用','分隔", required = true)
    public AjaxResult deleteTeam(@PathVariable String ids) {
        log.info("删除团队入参：{}", ids);
        teamManagementService.deleteTeamManagement(ids);
        return AjaxResult.success("删除成功");
    }

    @PostMapping("/updateTeam")
    @ApiOperation(value = "修改团队", notes = "修改团队")
    public AjaxResult updateTeam(@RequestBody @Valid AddTeamManagement teamManagement) {
        log.info("修改团队入参：{}", teamManagement);
        teamManagementService.updateTeamManagement(teamManagement);
        return AjaxResult.success("修改成功");
    }

    @GetMapping("/teamList")
    @ApiOperation(value = "查询团队信息列表")
    @ResponseBody
    public TableDataInfo teamList(@ApiParam(value = "地区") @RequestParam(value = "district",required = false) Integer district,
                                  @ApiParam(value = "团队名称") @RequestParam(value = "teamName",required = false) String teamName,
                                  @ApiParam(value = "负责人id") @RequestParam(value = "leaderId",required = false) Long leaderId,
                                  @ApiParam(value = "页面") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                  @ApiParam(value = "条数") @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                  @ApiParam(value = "开始时间") @RequestParam(value = "beginTime",required = false) String beginTime,
                                  @ApiParam(value = "结束时间") @RequestParam(value = "endTime",required = false) String endTime) {
        String getdistrict = null;
        if (district != null){
            getdistrict = getdistrict(district);
        }

        TeamManagementDto build = TeamManagementDto
                .builder()
                .districtName(getdistrict)
                .teamName(teamName)
                .leaderId(leaderId)
                .beginTime(beginTime)
                .endTime(endTime)
                .build();

        startPage();
        log.info("查询团队入参：{}", build);
        List<TeamManagementVo> teamManagementVos = teamManagementService.selectTeamManagement(build);
        return getDataTable(teamManagementVos);
    }

    @PostMapping("/addMember")
    @ApiOperation(value = "新增成员管理", notes = "新增成员管理")
    public AjaxResult addMember(@RequestBody @Valid MemberManagementDto memberManagementDto) {
        log.info("新增成员管理入参：{}", memberManagementDto);
        Integer memberManagement = memberManagementService.addMember(memberManagementDto);
        if (memberManagement == 1) {
            return AjaxResult.success();
        }
        return AjaxResult.error("新增成员管理失败");
    }

    @DeleteMapping("/deleteMember/{ids}")
    @ApiOperation(value = "删除成员管理", notes = "删除成员管理")
    @ApiImplicitParam(paramType = "path", name = "ids", value = "成员ID集合，多个用','分隔", required = true)
    public AjaxResult deleteMember(@PathVariable String ids) {
        log.info("删除成员入参：{}", ids);
        Integer i = memberManagementService.deleteMemberManagement(ids);
        if (i == 1) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PostMapping("/updateMember")
    @ApiOperation(value = "修改成员管理", notes = "修改成员管理")
    public AjaxResult updateMember(@RequestBody @Valid MemberManagementDto memberManagementDto) {
        log.info("修改成员管理入参：{}", memberManagementDto);
        Integer i = memberManagementService.updateMemberManagement(memberManagementDto);
        if (i == 1) {
            return AjaxResult.success();
        }
        return AjaxResult.error("成员修改失败");
    }

    @GetMapping("/memberList")
    @ApiOperation(value = "查询成员信息列表", notes = "查询成员信息列表")
    @ResponseBody
    public TableDataInfo memberList(@ApiParam(value = "业务员id") @RequestParam(value = "salesmanId",required = false) Long salesmanId,
                                               @ApiParam(value = "油企id") @RequestParam(value = "enterpriseId",required = false) Long enterpriseId,
                                               @ApiParam(value = "负责人") @RequestParam(value = "leader",required = false) String leader,
                                               @ApiParam(value = "业务人员") @RequestParam(value = "salesman",required = false) String salesman,
                                               @ApiParam(value = "页面") @RequestParam(value = "pageNum",required = false) Integer pageNum,
                                               @ApiParam(value = "条数") @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                               @ApiParam(value = "开始时间") @RequestParam(value = "beginTime",required = false) String beginTime,
                                               @ApiParam(value = "结束时间") @RequestParam(value = "endTime",required = false) String endTime) {
        MemberManagementQueryDto build = MemberManagementQueryDto.builder()
                .salesmanId(salesmanId)
                .enterpriseId(enterpriseId)
                .leader(leader)
                .salesman(salesman)
                .beginTime(beginTime)
                .endTime(endTime)
                .build();
        startPage();
        log.info("查询成员信息列表：{}", build);
        List<MemberManagementVo> memberManagementVos = memberManagementService.selectMemberManagement(build);
        return getDataTable(memberManagementVos);
    }


    @GetMapping("/userList")
    @ApiOperation(value = "获取等级为五或六的系统用户")
    @ResponseBody
    public AjaxResult userList(@ApiParam(value = "用户等级 1-5 2-6") @RequestParam(value = "level",required = false)Integer level) {
        List<SysUser> userLevel = sysUserService.getUserLevel(level);
        return AjaxResult.success(userLevel);
    }

    @GetMapping("/getLevelUserSix")
    @ApiOperation(value = "获取等级为六的系统用户")
    @ResponseBody
    public AjaxResult getLevelUserSix() {
        List<SysUser> userLevel = sysUserService.getLevelUserSix();
        return AjaxResult.success(userLevel);
    }

    public String getdistrict(Integer district){
        String districtString = "";
        switch (district){
            case 1:
                districtString = "华北地区";
                break;
            case 2:
                districtString = "华南地区";
                break;
            case 3:
                districtString="西南地区";
                break;
            case 4:
                districtString="西北地区";
                break;
            case 5:
                districtString="东北地区";
                break;
            default:
                throw new CustomException("传个正确的地区");
        }
        return districtString;
    }
    @GetMapping("/getRegionalReport")
    @ApiOperation(value = "大区权限数据报表")
    @ResponseBody
    public TableDataInfo getRegionalReport(@ApiParam(value = "大区") @RequestParam(value = "districtIds", required = false) List<Integer> districtIds,
                                           @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
                                           @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
                                           @ApiParam(value = "页面")     @RequestParam Integer pageNum,
                                           @ApiParam(value = "条数")    @RequestParam Integer pageSize,
                                           @ApiParam(value = "排序 0正序 1倒序") @RequestParam(value = "sorted",required = false) Integer sorted
    ) {
        log.info("大区权限数据报表入参：大区:{}，开始时间:{}，结束时间:{}，页面:{}，条数:{},排序：{}",districtIds,beginTime,endTime,pageNum,pageSize,sorted);
        List<RegionalReportVo> regionalReport = teamManagementService.getRegionalReport(districtIds,beginTime,endTime,pageNum,pageSize,sorted);
        return getTaleDataInfo(regionalReport,pageNum,pageSize);
    }

    @GetMapping("/getRegionalReportExport")
    @ApiOperation(value = "大区权限数据报表导出")
    public AjaxResult newSelectStatisticsPayOrderListExport(
            @ApiParam(value = "大区") @RequestParam(value = "districtIds", required = false) List<Integer> districtIds,
            @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
            @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "页面")     @RequestParam Integer pageNum,
            @ApiParam(value = "条数")    @RequestParam Integer pageSize,
            @ApiParam(value = "排序 0正序 1倒序") @RequestParam(value = "sorted",required = false) Integer sorted

    ) {
        List<RegionalReportVo> regionalReport = teamManagementService.getRegionalReport(districtIds,beginTime,endTime,pageNum,pageSize,sorted);
        ExcelUtil<RegionalReportVo> util = new ExcelUtil<>(RegionalReportVo.class);
        return util.exportExcel(regionalReport, "RegionalReportVo");
    }

    public TableDataInfo getTaleDataInfo(List<RegionalReportVo> payOrderList,Integer pageNum,Integer pageSize){
        //计算总记录数
        int total = payOrderList.size();
        //pageHelper无效，手动分页，流操作：sorted排序、skip跳记录和limit限制显示记录数
        List<RegionalReportVo> collect = payOrderList
                .stream()
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        //计算总页数
        int pageSum = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<RegionalReportVo> scorePageInfo = new PageInfo<>(collect);
        //总记录数
        scorePageInfo.setTotal(total);
        //总页数
        scorePageInfo.setPages(pageSum);
        //清除分页缓存
        PageHelper.clearPage();

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(collect);
        rspData.setTotal(total);
        return rspData;
    }
}
